#!/usr/bin/env bash
#. /etc/init.d/functions

############## author      : bruce [zhanpu@rd.hgits.cn]
############## date        : 2019-06-21
############## description : 服务启动脚本，无需要运维修改

# 返回值
RETVAL=$?
# 读取当前目录
readonly PWD=`pwd`
# 服务名称
readonly SERVER_NAME="xxl-rpc-admin"
# 返回上层目录
readonly SERVER_HOME="${PWD%/*}"
# 进程id
readonly PID_FILE="app.pid"

# 定义jvm参数
JVM_OPTION=

if [ -d "${SERVER_HOME}" ]; then
    JVM_OPTION="-server -Xms512m -Xmx512m -Dfile.encoding=UTF-8 -Dserver.name=${SERVER_NAME} -Djava.security.egd=file:///dev/urandom \
        	      -DproxySet=true -Dhttp.proxyHost=172.16.64.52 -Dhttp.proxyPort=3128 -Dhttps.proxyHost=172.16.64.52 -Dhttps.proxyPort=3128 -Dhttp.nonProxyHosts=localhost|172.16.64.*"
else
    echo $"'${SERVER_HOME}' not exists or is file ..."
    exit 1
fi

# 检查java是否安装命令
JRE_EXISTS=`which java | grep -v grep | awk '{ print $1 }'`
# 定义启动命令
START_COMMAND=

if [ -e "${JRE_EXISTS}" ]; then
    START_COMMAND="nohup java ${JVM_OPTION} -jar ${SERVER_NAME}.jar"
else
    echo $"jre not exists ..."
    exit 1
fi

# 检查pid（检查服务是否启动）
function check_pid() {
    if [ -f "${PID_FILE}" ]; then
        PID=`cat ${PID_FILE}`
        if [ -n "${PID}" ]; then
            RUNNING=`ps -p "${PID}"|grep -v "PID TTY" |wc -l`
            return ${RUNNING}
        fi
    fi
    return 0
}

# 查看服务状态
function status() {
    check_pid
    RUNNING=$?
    if [ ${RUNNING} -gt 0 ]; then
        echo -n $"${SERVER_NAME} now is running, pid="
        cat ${PID_FILE}
    else
        echo $"${SERVER_NAME} is stoped ..."
    fi
}

# 启动服务
function start() {
    check_pid
    RUNNING=$?
    if [ ${RUNNING} -gt 0 ]; then
        echo -n $"${SERVER_NAME} now is running already, pid="
        cat ${PID_FILE}
        return 1
    fi

    echo $"Started ${SERVER_NAME} service ..."
    # 启动命令并重定向
    ${START_COMMAND}>/dev/null 2>&1 &
    echo $! > "${PID_FILE}"
    sleep 2
    status
    echo $"Started ${SERVER_NAME} service successfully ..., pid=$!"
}

# 关闭服务
function stop() {
    PID=`cat ${PID_FILE}`
    kill -15 "${PID}"
    rm "${PID_FILE}"
    sleep 2
    status
    echo $"Stoped ${SERVER_NAME} service successfully ..."
}

# 重启服务
function restart() {
    stop
    sleep 1
    start
}

# 查看帮助
function help() {
    echo $"Usage: $0 {start|stop|restart|status}"
}

case "$1" in
start)
    start
    ;;
stop)
    stop
    ;;
restart)
    restart
    ;;
status)
    status
    ;;
*)
    help
    exit 1
    ;;
esac

exit $RETVAL